var imgdata = {'isconfile':'0','delfileurl':''}

$(function(){
    layui.use(['layer','form', 'table','laytpl','upload'], function(){
        var form = layui.form;
        var layer = layui.layer;
        var table = layui.table;
        var laytpl = layui.laytpl;
        var upload = layui.upload;
        
        $.ajaxSetup({
               headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
               }
        });

          table.render({
             elem: '#nevimsg'
             ,url: '/Xfindpeople' //数据接口
             ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                ,groups: 5 //只显示 1 个连续页码
                ,first: false //不显示首页
                ,last: false //不显示尾页
              }
              ,limit:10 //每页默认显示数
              ,limits:[5,10,20,50,100]
             ,cols: [[ //表头
               {field: 'id', title: 'ID', width:70, sort: true, align:'center'}
               ,{field: 'typename', title: '寻人类别', align:'center'}
               ,{field: 'miss_name', title: '失踪人姓名', align:'center'}
               ,{field: 'miss_pic', title: '失踪人照片',width:120, align:'center', templet:'#img'}
               ,{field: 'contact_name', title: '联系人姓名', align:'center'}
               ,{field: 'contact_phone', title: '联系人手机', align:'center'}
               ,{field: 'create_time', title: '发布时间', align:'center'}
               ,{field: 'showindex', title:'推荐',width:80, align:'center', templet:function(d){
                       return d.showindex == 0 ? '<a class="layui-btn  layui-btn-sm layui-btn-warm" lay-event="show" status="0">未推荐</a>' : '<a class="layui-btn  layui-btn-sm layui-btn-warm" lay-event="show" status="1">推荐中</a>';
                     } ,unresize: true}
               ,{field: 'is_shelf', title:'上下架',width:80, align:'center', templet:function(d){
                       return d.is_shelf == 0 ? '<a class="layui-btn  layui-btn-sm layui-btn-danger" lay-event="is_shelf" status="0">下架中</a>' : '<a class="layui-btn  layui-btn-sm layui-btn-danger" lay-event="is_shelf" status="1">上架中</a>';
                     } ,unresize: true}
               ,{field: 'status', title:'状态',width:80, align:'center', templet:function(d){
                       return d.status == 0 ? '<a class="layui-btn  layui-btn-sm layui-btn-danger" lay-event="statusfind" status="0">未找到</a>' : '<a class="layui-btn  layui-btn-sm layui-btn-danger" lay-event="statusfind" status="1">已找到</a>';
                     } ,unresize: true}
               ,{fixed: 'right', title:'编辑',width:150, align:'center', toolbar: '#barDemo'}

            ]]
            
          });

       //上传图片
       var uploadPic =  upload.render({
           elem: '.electpic'
          ,url: '/Uploads'
          ,auto: false //选择文件后不自动上传
          ,bindAction: '.addpic' //指向一个按钮触发上传
          ,headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
          ,accept: 'images'
          ,data: imgdata
          ,choose: function(obj){
            obj.preview(function(index, file, result){
              $("#imgadd").attr("src",result);
              $("#imgadd").css('display','block');
              
              $("#imgupdate").attr("src",result);
              $("#imgupdate").css('display','block');
              imgdata['delfileurl'] = $('input[name="peope_pic"]').val();
            });
          }
          ,done:function(res, index, upload){
              if (res.code == 200) {
                  $('.imgcurl').val(res.src);
                  layer.msg(res.msg,{time:1000,icon:1}) 
              }
          }
          ,error:function(index, upload){
              $('.chongbutd').css('display','block');
              $('#imgcurl').val('');
              $('#addpic2').click(function(){
                 uploadPic.upload();
              })

          }
        });  


        //添加弹窗
        $(".add-tan").click(function () {
          index = layer.open({
              type: 1,
              title: '新增信息',
              shadeClose: true,
              shade: 0.8,
              area: ['100%', '100%'],
              content: $('.add-data'),
              cancel: function (index, layero) {
                  if(confirm('确定要关闭么')){ //只有当点击confirm框的确定时，该层才会关闭
                      $("#imgadd").attr("src",'');
                      $("#imgadd").css('display','none');
                      $('#imgcurl').val('');
                      layer.close(index)
                  }
                return false;
              }
            });
          });

    function Phone(val)
    
    {
        var isMobilePhone = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
    
        var isFixMob= /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
    
        if(isFixMob.test(val)||isMobilePhone.test(val))
        {
            return true;
        }else{
            return false;
        }
    }
    var number_test = /^[0-9]*$/;


       //添加 监听提交
        form.on('submit(addbutton)', function(data){
              // console.log(data.field);
              if (!number_test.test(data.field.first_order)) { layer.alert('优先级排序应为数字'); return false };

              if(Phone(data.field.contact_phone) == false) {
                  layer.alert('联系电话格式错误');
                  return false;
              }
              if (/^[0-9]*$ /.test(data.field.first_order)) {
                layer.alert('优先级排序应为数字');
              }
               $.post('/XfindAdd',data.field,function(obj){
                    //根据返回结果作出相应处理
                    // alert(obj); return false;
                    if (obj.code == 400) 
                    {
                         layer.msg(obj.status+':'+obj.msg)
                    } else {
                         layer.msg(obj.status+':'+obj.msg,{time:1000,icon:1}, function(){
                            layer.close('index');
                            location.href = location.href;
                          }) 
                    }
                },'json');
                return false;//注释掉这行代码后，表单将会以普通方式提交表单，否则以ajax方式提交表单

        });


          //监听工具条  删除 修改功能
          table.on('tool(datalist)', function(obj)
          {
            var data = obj.data;

            if(obj.event === 'is_shelf')
            {
              var buttonmsg = $(this);
              var status = buttonmsg.attr('status');
              nowstatus = status == 0 ? 1 : 0;
              var buttontext = buttonmsg.attr('status') == 0 ? '上架中' : '下架中';
              $.post('/XfindchangeStatus', {id:data.id,is_shelf:nowstatus,types:1},function(obj){
                  //根据返回结果作出相应处理
                  if (obj.code == 200) 
                  {
                      layer.msg(obj.status+':'+obj.msg,{time:1000,icon:1}, function(){
                          buttonmsg.attr('status',nowstatus);
                          buttonmsg.text(buttontext);
                        }) 
                  } else if(obj.code == 400){
                       layer.msg(obj.status+':'+obj.msg)
                  }
              },'json');
              return false;
            }
            else if(obj.event === 'show')
            {
              var buttonmsg = $(this);
              var status = buttonmsg.attr('status');
              nowstatus = status == 0 ? 1 : 0;
              var buttontext = buttonmsg.attr('status') == 0 ? '推荐中' : '未推荐';
              $.post('/XfindchangeStatus', {id:data.id,showindex:nowstatus,types:2},function(obj){
                  //根据返回结果作出相应处理
                  if (obj.code == 200) 
                  {
                      layer.msg(obj.status+':'+obj.msg,{time:1000,icon:1}, function(){
                          buttonmsg.attr('status',nowstatus);
                          buttonmsg.text(buttontext);
                        }) 
                  } else if(obj.code == 400){
                       layer.msg(obj.status+':'+obj.msg)
                  }
              },'json');
              return false;


            } 
            else if(obj.event === 'statusfind')
            {
              var buttonmsg = $(this);
              var status = buttonmsg.attr('status');
              nowstatus = status == 0 ? 1 : 0;
              var buttontext = buttonmsg.attr('status') == 0 ? '已找到' : '未找到';
              $.post('/XfindchangeStatus', {id:data.id,status:nowstatus,types:3},function(obj){
                  //根据返回结果作出相应处理
                  if (obj.code == 200) 
                  {
                      layer.msg(obj.status+':'+obj.msg,{time:1000,icon:1}, function(){
                          buttonmsg.attr('status',nowstatus);
                          buttonmsg.text(buttontext);
                        }) 
                  } else if(obj.code == 400){
                       layer.msg(obj.status+':'+obj.msg)
                  }
              },'json');
              return false;


            } 
            else if (obj.event === 'del') 
            {
              if(confirm('删除后将无法恢复 确定要删除吗？')){ //只有当点击confirm框的确定时，该层才会关闭
                  $.get('/XfindDel', {id:data.id},function(objs){
                      //根据返回结果作出相应处理
                      if (objs.code == 200) 
                      {
                          layer.msg(objs.status+':'+objs.msg,{time:1000,icon:1}) 
                          obj.del();
                      } else if(objs.code == 400){
                           layer.msg(objs.status+':'+objs.msg)
                      }
                  },'json');
                  
                  
              }

            }
            else if(obj.event === 'edit')
            {           
                //修改赋值
                form.val('example',{
                        'id' : data.id,
                        'miss_name': data.miss_name,
                        'miss_sex': data.miss_sex,
                        'miss_home': data.miss_home,
                        'miss_barth': data.miss_barth,
                        'miss_high': data.miss_high,
                        'miss_date': data.miss_date,
                        'miss_access': data.miss_access,
                        'maybe_access': data.maybe_access,
                        'miss_money': data.money,
                        'find_type': data.find_type,
                        'miss_face': data.miss_face_text,
                        'miss_experience': data.miss_experience,
                        'others': data.other_desc,
                        'contact_name': data.contact_name,
                        'contact_net': data.contact_net,
                        'miss_desc': data.miss_desc,
                        'contact_phone': data.contact_phone,
                        'contact_email': data.contact_email,
                        'contact_other': data.contact_other,
                        'peope_pic': data.miss_pic,
                        'find_area': data.find_area,
                        'first_order': data.first_order,
                        'videourl': data.video_url,
                        'code': data.code,
                      });

                $("#imgupdate").css('display','block');
                url_path = $('#hidden_url').val();
                $('#imgupdate').attr('src',url_path+'/'+data.miss_pic);
                imgdata.delfileurl = data.miss_pic;  //上传图片赋值imgurl

                //编辑弹窗
                layer.open({
                    type: 1,
                    title: '编辑信息',
                    shadeClose: true,
                    shade: 0.8,
                    area: ['100%', '100%'],
                    content: $('.update-data'),
                    cancel: function (index, layero) {
                      if(confirm('请确定您数据无修改后关闭')){ //只有当点击confirm框的确定时，该层才会关闭
                          layer.close(index)
                          $("#imgupdate").css('display','none');
                          $('#imgupdate').attr('src','');
                          form.val('example',{
                            'id' : '',
                            'miss_name': '',
                            'miss_sex': '',
                            'miss_home': '',
                            'miss_barth': '',
                            'miss_high': '',
                            'miss_date': '',
                            'miss_access': '',
                            'maybe_access': '',
                            'miss_money': '',
                            'find_type': '',
                            'miss_face': '',
                            'miss_experience': '',
                            'others': '',
                            'contact_name': '',
                            'contact_net': '',
                            'contact_phone': '',
                            'contact_email': '',
                            'contact_other': '',
                            'peope_pic': '',
                            'find_area': '',
                            'first_oreder': '',
                            'videourl': '',
                            'code': '',
                          });
                      }
                      return false;
                    }
                });
                
            }
        });

        //修改  监听提交
        form.on('submit(update-button)', function(data){
            // console.log(JSON.stringify(data.field))
            // return false
            if (!number_test.test(data.field.first_order)) { layer.alert('优先级排序应为数字'); return false };
            if(Phone(data.field.contact_phone) == false) { layer.alert('联系电话格式错误'); return false };
            $.post('/XfindUpdate',data.field,function(obj){
                //根据返回结果作出相应处理
                // alert(obj);return false;
                    if (obj.code == 200) 
                    {
                        layer.msg(obj.status+':'+obj.msg,{time:1000,icon:1}, function(){
                            layer.close('edit');
                            location.href = location.href;
                          }) 
                    } else if(obj.code == 400){
                         layer.msg(obj.status+':'+obj.msg)
                    }
            },'json');
            return false;//注释掉这行代码后，表单将会以普通方式提交表单，否则以ajax方式提交表单
                
        });

        laytpl.config({
          open: '<<',
          close: '>>'
        });

          //点击刷新页面
          $(".layui-refresh").click(function () {
               location.href = location.href;
          });
      })
  })
